/**
  * @desc hash parameters
*/

const bcrypt = require('bcryptjs')
const _ = require('lodash')

const BCRYPT_WORK_FACTOR_BASE = 12
const BCRYPT_DATE_BASE = 1483228800000
const BCRYPT_WORK_INCREASE_INTERVAL = 47300000000

const hasher = password => new Promise((resolve, reject) => {
  const BCRYPT_CURRENT_DATE = new Date().getTime()
  const BCRYPT_WORK_INCREASE = Math
    .max(0, Math.floor((BCRYPT_CURRENT_DATE - BCRYPT_DATE_BASE) / BCRYPT_WORK_INCREASE_INTERVAL))
  const BCRYPT_WORK_FACTOR = Math.min(19, BCRYPT_WORK_FACTOR_BASE + BCRYPT_WORK_INCREASE)
  bcrypt.genSalt(BCRYPT_WORK_FACTOR, (genSaltError, salt) => {
    if (genSaltError) {
      return reject(genSaltError)
    }
    bcrypt.hash(password, salt, (hashError, hashedPassword) => {
      if (hashError) {
        return reject(hashError)
      }
      resolve(hashedPassword)
      return true
    })
    return true
  })
})

const hashBodyPassword = async (req, res, next) => {
  const originalPassword = _.get(req, 'body.password')
  if (originalPassword) {
    const hashedPassword = await hasher(originalPassword)
    req.body.password = hashedPassword
  }
  return next()
}

module.exports = hashBodyPassword
